package cetcbigdata.da.subject_integration_service.guangdong;

import cetcbigdata.da.base.DownloadAndUploadMinio;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Gutil {

    public static JSONObject getBaseInfo(String html){
        JSONObject base = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);

        //中介服务
        base.put("中介服务",
                isNotBlankOrNull(response.getJSONArray("agent_subject_list")) ? response.getJSONArray("agent_subject_list") : "无");

        //基础信息
        JSONObject basicInfo = new JSONObject();
        basicInfo.put("一件事名称", response.getString("subject_name"));
        basicInfo.put("一件事短名",
                isNotBlankOrNull(response.getString("short_name")) ? response.getString("short_name") : "无");
        basicInfo.put("事项类型", response.getString("special_item_type_text"));
        basicInfo.put("办理对象", response.getString("service_object_text"));
        basicInfo.put("承诺办结时限",
                response.getString("promise_time") + response.getString("promise_time_unit_text"));
        basicInfo.put("法定办结时限",
                response.getString("legal_time") + response.getString("legal_time_unit_text"));
        basicInfo.put("到办事现场次数", response.getString("present_movement_time"));
        basicInfo.put("必须现场办理原因",
                isNotBlankOrNull(response.getString("window_apply_reason")) ? response.getString("window_apply_reason") : "无");
        basicInfo.put("网办深度", response.getString("online_apply_depth_text"));
        basicInfo.put("办件类型",response.getString("handle_file_type_text"));
        basicInfo.put("牵头实施部门", response.getString("impl_org_name"));
        basicInfo.put("法定机关", response.getString("service_agent_type_text"));
        basicInfo.put("实施主体编码", response.getString("impl_org_tyshxydm"));
        basicInfo.put("是否支持预约办理", response.getString("appointment_text"));
        basicInfo.put("在线预约地址",
                isNotBlankOrNull(response.getString("appointment_url")) ? response.getString("appointment_url") : "无");
        basicInfo.put("是否支持物流快递", response.getString("express_text"));
        basicInfo.put("是否进驻政务大厅", response.getString("is_entry_center_text"));
        basicInfo.put("是否告知承诺制", response.getString("is_notify_promise_text"));
        basicInfo.put("办理形式", response.getString("application_channel_text"));
        basicInfo.put("基本编码", response.getString("basic_code"));
        basicInfo.put("实施编码", response.getString("service_code"));
        basicInfo.put("业务办理项编码",
                isNotBlankOrNull(response.getString("situation_code")) ? response.getString("situation_code") : "无");
        basicInfo.put("事项版本", response.getString("version"));
        basicInfo.put("委托部门",
                isNotBlankOrNull(response.getString("entrust_org")) ? response.getString("entrust_org") : "无");

        //联办机构
        List<JSONObject> organList= new ArrayList<>();
        JSONArray jointOrgan = response.getJSONArray("org_list");
        if (jointOrgan.isEmpty() && jointOrgan == null){
            basicInfo.put("联办机构", "无");
        }else {
            for (Object o : jointOrgan){
                JSONObject organ = new JSONObject();
                JSONObject joint = (JSONObject) o;
                organ.put("机构", joint.getString("org_name"));
                organList.add(organ);
            }
        }
        basicInfo.put("联办机构",organList);
        base.put("基础信息", basicInfo);

        //审批信息
        JSONObject approvalInfo = new JSONObject();
        approvalInfo.put("行使层级", response.getString("authority_level_text"));
        approvalInfo.put("权力来源", response.getString("power_source_text"));

        List<JSONObject> businessSys = new ArrayList<>();
        JSONArray sys = response.getJSONArray("biz_system_list");
        for (Object c : sys){
            JSONObject item = (JSONObject) c;
            JSONObject name = new JSONObject();
            name.put("系统", item.getString("name"));
            businessSys.add(name);
        }
        approvalInfo.put("业务系统", businessSys);
        base.put("审批信息", approvalInfo);

        //审批结果
        List<JSONObject> approvalResult = new ArrayList<>();
        JSONArray spxxOrg = response.getJSONArray("result_sample_list");
        if (spxxOrg == null || spxxOrg.size() == 0){
            base.put("审批结果", "无");
        }else {
            for (Object item : spxxOrg){
                JSONObject data = (JSONObject) item;
                JSONObject res = new JSONObject();
                res.put("名称", data.getString("name"));
                res.put("类型", data.getString("subject_result_type_text"));
                res.put("关联状态",
                        data.getInteger("is_relate_license").equals(0) ? "未关联电子证照" :
                                data.getInteger("is_relate_license").equals(1) ? "已关联电子证照" : null);

                //模板
                List<JSONObject> template = new ArrayList<>();
                JSONArray blankList = data.getJSONArray("blank_att_list");
                for (Object o : blankList) {
                    JSONObject templatedown = (JSONObject) o;
                    JSONObject templateOrg = new JSONObject();
                    templateOrg.put("名称", templatedown.getString("original_name"));
                    templateOrg.put("源地址", templatedown.getString("waiwang_url"));
                    templateOrg.put("minioId", fileDownloadAndUploadMinioGet(templatedown.getString("waiwang_url"),
                            templatedown.getString("original_name")));
                    template.add(templateOrg);
                }
                res.put("模板", template);

                //样例
                List<JSONObject> sample = new ArrayList<>();
                JSONArray sampleList = data.getJSONArray("sample_att_list");
                for (Object c : sampleList){
                    JSONObject sampledown = (JSONObject) c;
                    JSONObject sampleOrg = new JSONObject();
                    sampleOrg.put("名称", sampledown.getString("original_name"));
                    sampleOrg.put("源地址", sampledown.getString("waiwang_url"));
                    sampleOrg.put("minioId", fileDownloadAndUploadMinioGet(sampledown.getString("waiwang_url"),
                            sampledown.getString("original_name")));
                    sample.add(sampleOrg);
                }
                res.put("样例", sample);

                //关联事项
                List<JSONObject> common = new ArrayList<>();
                JSONArray commonList = data.getJSONArray("common_subject_list");
                for (Object a : commonList){
                    JSONObject commomOrg = (JSONObject) a;
                    JSONObject subjectName = new JSONObject();
                    subjectName.put("事项", commomOrg.getString("subject_name"));
                    common.add(subjectName);
                }
                res.put("关联事项", common);
                approvalResult.add(res);
            }
            base.put("审批结果", approvalResult);
        }

        //关联事项
        JSONObject relatedMatters = new JSONObject();
        JSONArray related = response.getJSONArray("common_subject_list");
        String movementTime = response.getString("present_movement_time");
        relatedMatters.put(" ", String.format("根据您选择的办事情形。涉及%s个关联事项。只需跑动%s次,即可一件事联办。" ,
                related != null ? related.size() : 0,
                movementTime != null ? movementTime : "零跑动"));

        List<JSONObject> oneThing = new ArrayList<>();
        for (Object b : related){
            JSONObject thingOrg = (JSONObject)b;
            JSONObject thing = new JSONObject();
            thing.put("名称", thingOrg.getString("subject_name"));
            thing.put("实施部门", thingOrg.getString("impl_org_name"));
            String subjectUrl = String.format("https://www.gdzwfw.gov.cn/portal/v2/guide/%s",
                    thingOrg.getString("subject_code"));
            thing.put("事项指南", subjectUrl);
            oneThing.add(thing);
            relatedMatters.put("一件事", oneThing);
        }
        base.put("关联事项", relatedMatters);

        //特别程序
        JSONObject SpcialFlow = new JSONObject();
        SpcialFlow.put("类型",
                isNotBlankOrNull(response.getString("special_flow_channel_text")) ?
                        response.getString("special_flow_channel_text") : "无");
        SpcialFlow.put("总时限", isNotBlankOrNull(response.getString("special_time")) ? response.getString("special_time") : "无");
        SpcialFlow.put("总时限说明",
                (isNotBlankOrNull(response.getInteger("special_time")) ? response.getInteger("special_time") : "0") +
                        response.getString("special_time_unit_text"));
        SpcialFlow.put("特别程序说明",
                isNotBlankOrNull(response.getString("special_flow_note")) ? response.getString("special_flow_note") : "无");
        base.put("特别程序", SpcialFlow);

//        System.out.println(base);
        return base;
    }

    public static JSONObject getScopesInfo(String html){
        JSONObject scopes = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);

        //受理范围
        JSONObject AcceptanceScope = new JSONObject();
        AcceptanceScope.put("服务对象",
                isNotBlankOrNull(response.getString("service_object_text")) ? response.getString("service_object_text") : "无");
        AcceptanceScope.put("面向个人/法人事项主题分类",
                isNotBlankOrNull(response.getString("enterprise_special_catalog")) ?
                        response.getString("enterprise_special_catalog") : "无");
        AcceptanceScope.put("申请内容",
                isNotBlankOrNull(response.getString("sqnr")) ?  response.getString("sqnr") : "无");
        scopes.put("受理范围", AcceptanceScope);

        //受理条件
        scopes.put("受理条件", response.getString("conditions"));

        //
        return scopes;
    }

    public static JSONObject getHandlingProcedures(String html){
        JSONObject handlingProcedures = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);

        //网上办理流程
        JSONObject onlineFlow = new JSONObject();
        onlineFlow.put("内容",
                isNotBlankOrNull(response.getString("online_flow")) ? response.getString("online_flow") : "暂无");

        //查看详细流程
        JSONArray onlineList = response.getJSONArray("online_flow_pic_att_list");
        JSONObject OnlineFlow = new JSONObject();
        if (onlineList.size() == 0 && onlineList == null){
            OnlineFlow.put("查看详细流程", "");
        }else {
            for (Object o : onlineList){
                JSONObject item = (JSONObject) o;
                OnlineFlow.put("名称", item.getString("original_name"));
                OnlineFlow.put("源地址", item.getString("waiwang_url"));
                OnlineFlow.put("miniid",
                        fileDownloadAndUploadMinioGet(item.getString("waiwang_url"), item.getString("original_name")));
                onlineFlow.put("查看详细流程", OnlineFlow);
            }
        }
        handlingProcedures.put("网上办理流程", onlineFlow);

        //线下办理流程
        JSONObject WindowFlow = new JSONObject();
        WindowFlow.put("内容",response.getString("window_flow"));

        //查看详细流程
        JSONArray windowList = response.getJSONArray("window_flow_pic_att_list");
        JSONObject windowFlow = new JSONObject();
        for (Object c : windowList){
            JSONObject item = (JSONObject) c;
            windowFlow.put("名称", item.getString("original_name"));
            windowFlow.put("源地址", item.getString("waiwang_url"));
            windowFlow.put("miniid",
                    fileDownloadAndUploadMinioGet(item.getString("waiwang_url"), item.getString("original_name")));
            WindowFlow.put("查看详细流程", windowFlow);
        }
        handlingProcedures.put("线下办理流程", WindowFlow);

        return handlingProcedures;
    }

    public static List<JSONObject> getMaterialAll(String html){
        List<JSONObject> material = new ArrayList<>();
        JSONObject response = JSONObject.parseObject(html);

        JSONArray data = response.getJSONArray("submit_material_list");
        //材料信息
        if (data == null || data.size() == 0){
            JSONObject materialItem = new JSONObject();
            materialItem.put("材料信息", "无");
            material.add(materialItem);
        }else {
            for (Object o : data){
                JSONObject items = (JSONObject) o;
                JSONObject materialItems = new JSONObject();
                //材料名称
                materialItems.put("材料名称", items.getString("document_name"));
                //材料形式
                materialItems.put("材料形式", "原件: " + items.getInteger("origin_count")
                        + "复印件: " + items.getInteger("origin_count") + items.getString("document_media_text"));

                //材料要求
                JSONObject otherReq = new JSONObject();
                otherReq.put("材料类型", items.getString("material_type_text"));
                otherReq.put("材料形式", items.getString("document_media_text"));
                otherReq.put("纸质材料规格", isNotBlankOrNull(items.getString("paper_document_specification")) ?
                        items.getString("paper_document_specification") : "无");
                otherReq.put("是否免提交", items.getString("submission_required_text"));
                materialItems.put("材料要求", items.getString("document_need_type_text") + "，其他要求：" + otherReq);

                //材料下载
                JSONObject MaterialDownload = new JSONObject();
                //空白表格
                List<JSONObject> BlankAttList = new ArrayList<>();
                JSONArray blankOrg = items.getJSONArray("blank_att_list");
                for (Object b : blankOrg){
                    JSONObject blankData = (JSONObject) b;
                    JSONObject blank = new JSONObject();
                    blank.put("名称", blankData.getString("original_name"));
                    blank.put("源地址", blankData.getString("waiwang_url"));
                    blank.put("minioId",
                            fileDownloadAndUploadMinioGet(blankData.getString("waiwang_url"), blankData.getString("original_name")));
                    BlankAttList.add(blank);
                }

                //示例样本
                List<JSONObject> SampleAttList = new ArrayList<>();
                JSONArray sampleOrg = items.getJSONArray("sample_att_list");
                for (Object s : sampleOrg){
                    JSONObject sampleData = (JSONObject) s;
                    JSONObject sample = new JSONObject();
                    sample.put("名称", sampleData.getString("original_name"));
                    sample.put("源地址", sampleData.getString("waiwang_url"));
                    sample.put("minioId",
                            fileDownloadAndUploadMinioGet(sampleData.getString("waiwang_url"), sampleData.getString("original_name")));
                    SampleAttList.add(sample);
                }
                MaterialDownload.put("空白表格", BlankAttList);
                MaterialDownload.put("示例样本", SampleAttList);
                materialItems.put("材料下载", MaterialDownload);

                //其他信息
                JSONObject OtherInfo = new JSONObject();
                OtherInfo.put("填报须知",
                        isNotBlankOrNull(items.getString("fill_explain")) ? items.getString("fill_explain") : "无");
                OtherInfo.put("来源渠道名称",
                        isNotBlankOrNull(items.getString("document_source_text")) ? items.getString("document_source_text") : "无");
                OtherInfo.put("备注信息",
                        isNotBlankOrNull(items.getString("note")) ? items.getString("note") : "无");
                materialItems.put("其他信息", OtherInfo);

                //关联事项
                JSONArray relateOrg = items.getJSONArray("common_subject_list");
                List<String> relateList = new ArrayList<>();
                for (Object r : relateOrg){
                    JSONObject relatrDate = (JSONObject) r;
                    relateList.add(relatrDate.getString("subject_name"));
                }
                materialItems.put("关联事项", relateList);

                //查看依据
                List<JSONObject> viewBasis = new ArrayList<>();
                JSONObject view = new JSONObject();
                JSONArray agentListOrg = items.getJSONArray("clause_list");
                for (Object a : agentListOrg){
                    JSONObject agentData = (JSONObject) a;
                    JSONObject Basis = new JSONObject();
                    Basis.put("法律法规名称", agentData.getString("legal_name"));
                    Basis.put("依据文号", agentData.getString("reference_number"));
                    Basis.put("条款号", agentData.getString("clause_number"));
                    Basis.put("条款内容", agentData.getString("content"));
                    view.put("详细依据", Basis);
                    viewBasis.add(view);
                }
                materialItems.put("查看依据", viewBasis);
                material.add(materialItems);
            }
        }

        JSONArray fromLIst = response.getJSONArray("submit_form_list");
        if (fromLIst == null || fromLIst.size() == 0){
            JSONObject FromItem = new JSONObject();
            FromItem.put("材料信息", "无");
            material.add(FromItem);
        }else {
            for (Object o : fromLIst){
                JSONObject items = (JSONObject) o;
                JSONObject FromItems = new JSONObject();
                //材料名称
                FromItems.put("材料名称", items.getString("document_name"));
                //材料形式
                FromItems.put("材料形式", "原件: " + items.getInteger("origin_count")
                        + "复印件: " + items.getInteger("origin_count") + items.getString("document_media_text"));

                //材料要求
                JSONObject otherReq = new JSONObject();
                otherReq.put("材料类型", items.getString("material_type_text"));
                otherReq.put("材料形式", items.getString("document_media_text"));
                otherReq.put("纸质材料规格", isNotBlankOrNull(items.getString("paper_document_specification")) ?
                        items.getString("paper_document_specification") : "无");
                otherReq.put("是否免提交", items.getString("submission_required_text"));
                FromItems.put("材料要求", items.getString("document_need_type_text") + "，其他要求：" + otherReq);

                //材料下载
                JSONObject MaterialDownload = new JSONObject();
                //空白表格
                List<JSONObject> BlankAttList = new ArrayList<>();
                JSONArray blankOrg = items.getJSONArray("blank_att_list");
                for (Object b : blankOrg){
                    JSONObject blankData = (JSONObject) b;
                    JSONObject blank = new JSONObject();
                    blank.put("名称", blankData.getString("original_name"));
                    blank.put("源地址", blankData.getString("waiwang_url"));
                    blank.put("minioId",
                            fileDownloadAndUploadMinioGet(blankData.getString("waiwang_url"), blankData.getString("original_name")));
                    BlankAttList.add(blank);
                }

                //示例样本
                List<JSONObject> SampleAttList = new ArrayList<>();
                JSONArray sampleOrg = items.getJSONArray("sample_att_list");
                for (Object s : sampleOrg){
                    JSONObject sampleData = (JSONObject) s;
                    JSONObject sample = new JSONObject();
                    sample.put("名称", sampleData.getString("original_name"));
                    sample.put("源地址", sampleData.getString("waiwang_url"));
                    sample.put("minioId",
                            fileDownloadAndUploadMinioGet(sampleData.getString("waiwang_url"), sampleData.getString("original_name")));
                    SampleAttList.add(sample);
                }
                MaterialDownload.put("空白表格", BlankAttList);
                MaterialDownload.put("示例样本", SampleAttList);
                FromItems.put("材料下载", MaterialDownload);

                //其他信息
                JSONObject OtherInfo = new JSONObject();
                OtherInfo.put("填报须知",
                        isNotBlankOrNull(items.getString("fill_explain")) ? items.getString("fill_explain") : "无");
                OtherInfo.put("来源渠道名称",
                        isNotBlankOrNull(items.getString("document_source_text")) ? items.getString("document_source_text") : "无");
                OtherInfo.put("备注信息",
                        isNotBlankOrNull(items.getString("note")) ? items.getString("note") : "无");
                FromItems.put("其他信息", OtherInfo);

                //关联事项
                JSONArray relateOrg = items.getJSONArray("common_subject_list");
                List<String> relateList = new ArrayList<>();
                for (Object r : relateOrg){
                    JSONObject relatrDate = (JSONObject) r;
                    relateList.add(relatrDate.getString("subject_name"));
                }
                FromItems.put("关联事项", relateList);

                //中介服务
                List<JSONObject> agentListOut = new ArrayList<>();
                JSONObject agent = new JSONObject();
                JSONArray agentListOrg = items.getJSONArray("clause_list");
                for (Object a : agentListOrg){
                    JSONObject agentData = (JSONObject) a;
                    JSONObject Basis = new JSONObject();
                    Basis.put("法律法规名称", agentData.getString("legal_name"));
                    Basis.put("依据文号", agentData.getString("reference_number"));
                    Basis.put("条款号", agentData.getString("clause_number"));
                    Basis.put("条款内容", agentData.getString("content"));
                    agent.put("详细依据", Basis);
                    agentListOut.add(agent);
                }
                FromItems.put("中介服务", agentListOut);
                material.add(FromItems);
            }
        }







        return material;
    }

    public static JSONArray getChargeInfo(String html){
        JSONObject response = JSONObject.parseObject(html);


        return isNotBlankOrNull(response.getJSONArray("charge_scale_list")) ?
                response.getJSONArray("charge_scale_list") : new JSONArray();
    }

    public static JSONObject getOtherInfo (String html){
        JSONObject OtherInfo = new JSONObject();
        JSONObject response = JSONObject.parseObject(html);

        //设定依据
        List<JSONObject> SettingBasis = new ArrayList<>();
        JSONArray basisList = response.getJSONArray("clause_list");
        for (Object items : basisList){
            JSONObject basisOrg = (JSONObject) items;
            JSONObject basisInfo = new JSONObject();
            basisInfo.put("法律法规名称", basisOrg.getString("legal_name"));
            basisInfo.put("依据文号", basisOrg.getString("reference_number"));
            basisInfo.put("条款号", basisOrg.getString("clause_number"));
            basisInfo.put("颁布机关", basisOrg.getString("issuing_body"));
            basisInfo.put("条款内容", basisOrg.getString("content"));
            SettingBasis.add(basisInfo);
        }
        OtherInfo.put("设定依据", SettingBasis);

        //权利与义务
        JSONObject RightDuties = new JSONObject();
        RightDuties.put("申请人依法享有以下权利", response.getString("applicant_power"));
        RightDuties.put("申请人依法履行以下义务", response.getString("applicant_obligations"));
        OtherInfo.put("权利与义务", RightDuties);

        //法律救济
        JSONObject legalRemedy = new JSONObject();
        //行政复议
        JSONObject reconsider = new JSONObject();
        reconsider.put("部门", response.getString("xzfybm"));
        reconsider.put("地址", response.getString("xzfydz"));
        reconsider.put("电话", response.getString("xzfydh"));
        reconsider.put("网址",
                isNotBlankOrNull(response.getString("xzfywz")) ? response.getString("xzfywz") : "无");
        legalRemedy.put("行政复议", reconsider);
        //行政诉讼
        JSONObject lawsuit = new JSONObject();
        lawsuit.put("部门", response.getString("xzssbm"));
        lawsuit.put("电话", response.getString("xzssdh"));
        lawsuit.put("地址", response.getString("xzssdz"));
        lawsuit.put("网址",
                isNotBlankOrNull(response.getString("xzsswz")) ? response.getString("xzsswz") : "无");
        legalRemedy.put("行政诉讼", lawsuit);
        OtherInfo.put("法律救济", legalRemedy);

        return OtherInfo;
    }



    public static String fileDownloadAndUploadMinioGet (String url, String docName){
        // docName 文件名要带后缀
        try {
            JSONObject headers = new JSONObject();
            return DownloadAndUploadMinio.getInstance().downloadGet(
                    url,
                    headers,
                    new JSONObject(),
                    docName
            );
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "";
    }

    /*******
     *  判断是否为null 或者 空字符串
     * @param str
     * @return
     */
    public static boolean isNotBlankOrNull (Object str){
        return str != null && !str.toString().equals("");
    }
}
